<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>课翼管家</title>
    <script src="js/tailwindcss_3.4.17.js"></script>
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/font-awesome.all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#F97316',
                        danger: '#EF4444',
                        neutral: '#64748B',
                        sun: '#FFB800',
                        moon: '#94A3B8',
                        star: '#FBBF24',
                        trophy: '#C9B037', // 奖杯金色
                        gold: '#FFD700',    // 金牌颜色
                        silver: '#E5E7EB',  // 银牌颜色
                        bronze: '#CD7F32',  // 铜牌颜色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        :root {
            --primary: #6366f1;      /* 主色调 - 靛蓝 */
            --secondary: #8b5cf6;    /* 次要色 - 紫色 */
            --accent: #06b6d4;       /* 强调色 - 青色 */
            --success: #10b981;      /* 成功色 - 翡翠绿 */
            --warning: #f59e0b;      /* 警告色 - 琥珀 */
        }
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
            }
            .fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            .pulse {
                animation: pulse 1.5s infinite;
            }
            .spin-in {
                animation: spinIn 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            }
            .bounce-in {
                animation: bounceIn 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            }
            .scale-in {
                animation: scaleIn 0.3s ease-out;
            }
            .scale-out {
                animation: scaleOut 0.3s ease-in;
            }
            .name-scroll {
                animation: nameScroll 0.1s linear infinite;
            }
            .slow-down {
                animation: slowDown 2s ease-out forwards;
            }
            .shine {
                animation: shine 1s ease-in-out;
            }
            .trophy-shine {
                animation: trophyShine 2s infinite;
            }
            .avatar-upload {
                position: relative;
                overflow: hidden;
                cursor: pointer;
            }
            .avatar-upload input {
                position: absolute;
                top: 0;
                right: 0;
                min-width: 100%;
                min-height: 100%;
                font-size: 100px;
                opacity: 0;
                cursor: pointer;
            }
            .rank-badge {
                position: absolute;
                top: -8px;
                right: -8px;
                width: 28px;
                height: 28px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: bold;
                color: white;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                z-index: 10;
            }
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        @keyframes spinIn {
            0% { transform: scale(0) rotate(0deg); opacity: 0; }
            70% { transform: scale(1.1) rotate(10deg); }
            100% { transform: scale(1) rotate(0deg); opacity: 1; }
        }
        @keyframes bounceIn {
            0% { transform: scale(0); opacity: 0; }
            60% { transform: scale(1.1); }
            100% { transform: scale(1); opacity: 1; }
        }
        @keyframes scaleIn {
            from { transform: scale(0.8); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        @keyframes scaleOut {
            from { transform: scale(1); opacity: 1; }
            to { transform: scale(0.8); opacity: 0; }
        }
        @keyframes nameScroll {
            0% { transform: translateY(0); }
            100% { transform: translateY(-20px); }
        }
        @keyframes slowDown {
            0% { animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275); animation-duration: 0.1s; }
            50% { animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275); animation-duration: 0.3s; }
            100% { animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275); animation-duration: 1s; }
        }
        @keyframes shine {
            0% { transform: scale(1); filter: brightness(1); }
            50% { transform: scale(1.2); filter: brightness(1.5); }
            100% { transform: scale(1); filter: brightness(1); }
        }
        @keyframes trophyShine {
            0% { filter: brightness(1); transform: rotate(0deg); }
            50% { filter: brightness(1.3); transform: rotate(5deg); }
            100% { filter: brightness(1); transform: rotate(0deg); }
        }
         /* 增强版全屏星星爆炸动画 */
        @keyframes starExplosion {
            0% {
                transform: translate(-50%, -50%) scale(0) rotate(0deg);
                opacity: 1;
                filter: brightness(2) drop-shadow(0 0 10px currentColor);
            }
            30% {
                transform: translate(-50%, -50%) scale(1.5) rotate(108deg);
                opacity: 1;
                filter: brightness(3) drop-shadow(0 0 20px currentColor);
            }
            100% {
                transform: translate(calc(var(--tx) - 50%), calc(var(--ty) - 50%)) scale(0) rotate(720deg);
                opacity: 0;
                filter: brightness(1) drop-shadow(0 0 5px currentColor);
            }
        }

        /* 增强版星星样式 - 多种形状 */
        .star-particle {
            position: fixed;
            width: 20px;
            height: 20px;
            background: linear-gradient(45deg, #FFD700, #FFA500);
            clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
            transform-origin: center center;
            z-index: 9999;
            pointer-events: none;
            box-shadow: 0 0 15px currentColor;
        }

        /* 大星星样式 */
        .star-particle.large {
            width: 40px;
            height: 40px;
            filter: blur(0.5px);
        }

        /* 小星星样式 */
        .star-particle.small {
            width: 12px;
            height: 12px;
        }

        /* 心形星星 */
        .star-particle.heart {
            clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 50% 75%, 18% 100%, 0% 38%);
            background: linear-gradient(45deg, #FF69B4, #FF1493);
        }

        /* 钻石形状 */
        .star-particle.diamond {
            clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
            background: linear-gradient(45deg, #00CED1, #40E0D0);
        }

        /* 增强成功特效 */
        .success-glow {
            animation: successGlow 1.2s ease-in-out;
            box-shadow: 0 0 30px rgba(255, 215, 0, 0.8);
            transform-origin: center;
        }

        @keyframes successGlow {
            0% {
                box-shadow: 0 0 0 rgba(255, 215, 0, 0.6);
                transform: scale(1);
                filter: brightness(1);
            }
            25% {
                box-shadow: 0 0 50px rgba(255, 215, 0, 1);
                transform: scale(1.05);
                filter: brightness(1.2);
            }
            50% {
                box-shadow: 0 0 80px rgba(255, 215, 0, 0.9);
                transform: scale(1.08);
                filter: brightness(1.4);
            }
            75% {
                box-shadow: 0 0 50px rgba(255, 215, 0, 0.7);
                transform: scale(1.05);
                filter: brightness(1.2);
            }
            100% {
                box-shadow: 0 0 0 rgba(255, 215, 0, 0);
                transform: scale(1);
                filter: brightness(1);
            }
        }

        /* 背景闪光效果 */
        .screen-flash {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle, rgba(255, 215, 0, 0.2) 0%, transparent 70%);
            z-index: 9998;
            pointer-events: none;
            animation: screenFlash 1.5s ease-out;
        }

        @keyframes screenFlash {
            0% { opacity: 0; }
            20% { opacity: 1; }
            100% { opacity: 0; }
        }

        /* 导航按钮基础样式 */
        .nav-btn {
            position: relative;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 0.75rem;
            color: rgba(255, 255, 255, 0.9);
            transition: all 0.3s ease;
        }

        .nav-btn:hover {
            background-color: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(4px);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        /* 图标容器 */
        .nav-icon {
            width: 2rem;
            height: 2rem;
            border-radius: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        /* 标签样式 */
        .nav-label {
            font-weight: 500;
            font-size: 0.875rem;
        }

        /* 添加按钮样式 */
        .nav-btn-add {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 0.75rem;
            background-color: rgba(255, 255, 255, 0.2);
            color: white;
            transition: all 0.3s ease;
            backdrop-filter: blur(4px);
        }

        .nav-btn-add:hover {
            background-color: rgba(255, 255, 255, 0.3);
        }

        .nav-btn-add.secondary {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .nav-btn-add.secondary:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        /* 下拉菜单样式 */
        .dropdown-menu {
            position: absolute;
            top: 100%;
            margin-top: 0.5rem;
            width: 14rem;
            background-color: white;
            border-radius: 0.75rem;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
            overflow: hidden;
            z-index: 50;
            opacity: 0;
            transform: translateY(-10px);
            transition: all 0.3s ease;
        }

        .group:hover .dropdown-menu {
            opacity: 1;
            transform: translateY(0);
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem 1rem;
            transition: background-color 0.15s ease;
        }

        .dropdown-item:hover {
            background-color: rgb(249, 250, 251);
        }
        /* 移动端底部导航 */
        .mobile-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(to right, var(--indigo-600), var(--purple-600));
            backdrop-filter: blur(8px);
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .mobile-nav-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 0.25rem;
            padding: 0.5rem;
        }

        .mobile-nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 0.5rem 0;
            color: rgba(255, 255, 255, 0.8);
            transition: all 0.15s ease;
        }

        .mobile-nav-item:hover {
            color: white;
        }

        .mobile-nav-item.active {
            color: white;
        }

        .mobile-nav-icon {
            font-size: 1.25rem;
            margin-bottom: 0.25rem;
        }

        .mobile-nav-label {
            font-size: 0.75rem;
            font-weight: 500;
        }

        /* 悬停波纹效果 */
        .mobile-nav-item::before {
            content: '';
            position: absolute;
            inset: 0;
            border-radius: 0.75rem;
            background-color: rgba(255, 255, 255, 0);
            transition: all 0.3s ease;
        }

        .mobile-nav-item:hover::before {
            background-color: rgba(255, 255, 255, 0.1);
            animation: ripple 0.6s ease-out;
        }

        @keyframes ripple {
            0% { transform: scale(0.8); opacity: 1; }
            100% { transform: scale(1.2); opacity: 0; }
        }

        /* 徽章通知 */
        .mobile-nav-badge {
            position: absolute;
            top: -0.25rem;
            right: -0.25rem;
            width: 1.25rem;
            height: 1.25rem;
            background-color: rgb(239, 68, 68);
            color: white;
            font-size: 0.75rem;
            border-radius: 9999px;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        /* 字母索引侧边栏 */
        .alphabet-sidebar {
            position: fixed;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 40;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            padding: 12px 8px;
        }

        .alphabet-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }

        .alphabet-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2px;
            margin-bottom: 4px;
            font-size: 9px;
            color: var(--primary);
            font-weight: 600;
        }

        .alphabet-header i {
            font-size: 12px;
        }

        /* 两列布局的字母列表 */
        .alphabet-list.two-columns {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 2px;
            width: 100%;
            padding: 0 4px;
        }

        .alphabet-list {
            display: flex;
            flex-direction: column;
            gap: 1px;
        }

        .alphabet-btn {
            width: 28px;
            height: 28px;
            border: none;
            background: transparent;
            color: #64748b;
            font-size: 12px;
            font-weight: 600;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

         .alphabet-btn:hover {
            background: #f1f5f9;
            color: var(--primary);
            transform: scale(1.05); /* 减小放大效果 */
        }

        .alphabet-btn.active {
            background: var(--primary);
            color: white;
            transform: scale(1.05);
        }

        .alphabet-clear {
            margin-top: 4px; /* 减小间距 */
            padding: 4px 6px; /* 减小按钮尺寸 */
            border: none;
            background: #f8fafc;
            color: #64748b;
            font-size: 9px; /* 减小字体 */
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 2px;
        }

        .alphabet-clear:hover {
            background: #e2e8f0;
            color: #475569;
        }

        /* 响应式设计 - 进一步优化 */
        @media (max-width: 1280px) {
            .alphabet-sidebar {
                left: 10px;
                padding: 10px 5px;
            }
            
            .alphabet-btn {
                width: 26px;
                height: 26px;
                font-size: 10px;
            }
        }

        @media (max-width: 1024px) {
            .alphabet-sidebar {
                left: 5px;
                padding: 8px 4px;
            }
            
            .alphabet-btn {
                width: 24px;
                height: 24px;
                font-size: 9px;
            }
            
            .alphabet-header {
                font-size: 8px;
            }
            
            .alphabet-header i {
                font-size: 10px;
            }
        }

        @media (max-width: 768px) {
            .alphabet-sidebar {
                display: none;
            }
        }

        /* 主内容区域适配 - 调整边距 */
        main {
            margin-left: 80px; /* 字母索引侧边栏宽度 */
            transition: margin-left 0.3s ease;
        }

        @media (max-width: 1280px) {
            main {
                margin-left: 70px;
            }
        }

        @media (max-width: 1024px) {
            main {
                margin-left: 60px; /* 减小边距 */
            }
        }

        @media (max-width: 768px) {
            main {
                margin-left: 0;
            }
        }

        /* 学生卡片响应式调整 */
        @media (max-width: 640px) {
            #studentList {
                grid-template-columns: 1fr;
            }
        }

        @media (min-width: 641px) and (max-width: 1024px) {
            #studentList {
                grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            }
        }

        /* 统计卡片响应式调整 */
        @media (max-width: 640px) {
            .grid-cols-1.md\:grid-cols-3 {
                grid-template-columns: 1fr;
            }
        }

        /* 顶部导航响应式调整 */
        @media (max-width: 1024px) {
            .nav-btn .nav-label {
                display: none;
            }
            
            .nav-btn {
                padding: 0.5rem;
            }
            
            .nav-btn-add {
                padding: 0.5rem;
            }
            
            .nav-btn-add span {
                display: none;
            }
        }
    </style>
</head>

<body class="bg-gray-50 font-sans min-h-screen">
    <!-- 顶部导航 -->
    <header class="bg-gradient-to-r from-indigo-600 to-purple-600 shadow-xl">
        <div class="container mx-auto px-6 py-4">
            <div class="flex items-center justify-between">
                <!-- Logo区域 -->
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-graduation-cap text-white text-xl"></i>
                    </div>
                    <div>
                        <h1 class="text-white font-bold text-xl">课翼管家</h1>
                        <p class="text-white/70 text-xs">智能学生管理</p>
                    </div>
                </div>

                <!-- 功能菜单组 -->
                <nav class="flex items-center space-x-2">
                    <!-- 作业管理 -->
                    <button class="nav-btn group" onclick="window.location.href='家庭作业.html'">
                        <div class="nav-icon bg-gradient-to-r from-blue-500 to-blue-500">
                            <i class="fas fa-book-open"></i>
                        </div>
                        <span class="nav-label">家庭作业</span>
                    </button>

                    <!-- 抽奖 -->
                    <button class="nav-btn group" id="flipCardBtn">
                        <div class="nav-icon bg-gradient-to-r from-pink-500 to-rose-500">
                            <i class="fas fa-gift"></i>
                        </div>
                        <span class="nav-label">幸运抽奖</span>
                    </button>

                    <!-- 随机点名 -->
                    <button class="nav-btn group" id="randomCallBtn">
                        <div class="nav-icon bg-gradient-to-r from-cyan-500 to-blue-500">
                            <i class="fas fa-random"></i>
                        </div>
                        <span class="nav-label">随机点名</span>
                    </button>

                    <!-- 数据管理下拉菜单 -->
                    <div class="relative group" id="dataManageContainer">
                        <button class="nav-btn" id="dataManageBtn">
                            <div class="nav-icon bg-gradient-to-r from-amber-500 to-orange-500">
                                <i class="fas fa-database"></i>
                            </div>
                            <span class="nav-label">数据管理</span>
                            <i class="fas fa-chevron-down text-xs ml-1 transition-transform group-hover:rotate-180"></i>
                        </button>

                        <!-- 下拉菜单 -->
                        <div class="dropdown-menu" id="dataMenu">
                            <a href="#" class="dropdown-item" id="exportDataBtn">
                                <i class="fas fa-download text-blue-500"></i>
                                <span>导出数据</span>
                            </a>
                            <a href="#" class="dropdown-item" id="importDataBtn">
                                <i class="fas fa-upload text-green-500"></i>
                                <span>导入数据</span>
                                <input id="importDataInput" type="file" accept=".json" class="hidden">
                            </a>
                            <a href="#" class="dropdown-item text-red-600" id="clearDataBtn">
                                <i class="fas fa-trash text-red-500"></i>
                                <span>清空数据</span>
                            </a>
                        </div>
                    </div>

                    <!-- 分割线 -->
                    <div class="w-px h-6 bg-white/20"></div>

                    <!-- 添加学生 -->
                    <button class="nav-btn-add" id="addStudentBtn">
                        <i class="fas fa-plus"></i>
                        <span>添加学生</span>
                    </button>

                    <!-- 批量添加 -->
                    <button class="nav-btn-add secondary" id="batchAddStudentBtn">
                        <i class="fas fa-users"></i>
                        <span>批量添加</span>
                    </button>
                </nav>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-6">
        <!-- 字母索引侧边栏 -->
        <aside class="alphabet-sidebar" >
            <div class="alphabet-container">
                <div class="alphabet-list two-columns">
                    <button class="alphabet-btn" data-letter="A">A</button>
                    <button class="alphabet-btn" data-letter="B">B</button>
                    <button class="alphabet-btn" data-letter="C">C</button>
                    <button class="alphabet-btn" data-letter="D">D</button>
                    <button class="alphabet-btn" data-letter="E">E</button>
                    <button class="alphabet-btn" data-letter="F">F</button>
                    <button class="alphabet-btn" data-letter="G">G</button>
                    <button class="alphabet-btn" data-letter="H">H</button>
                    <button class="alphabet-btn" data-letter="I">I</button>
                    <button class="alphabet-btn" data-letter="J">J</button>
                    <button class="alphabet-btn" data-letter="K">K</button>
                    <button class="alphabet-btn" data-letter="L">L</button>
                    <button class="alphabet-btn" data-letter="M">M</button>
                    <button class="alphabet-btn" data-letter="N">N</button>
                    <button class="alphabet-btn" data-letter="O">O</button>
                    <button class="alphabet-btn" data-letter="P">P</button>
                    <button class="alphabet-btn" data-letter="Q">Q</button>
                    <button class="alphabet-btn" data-letter="R">R</button>
                    <button class="alphabet-btn" data-letter="S">S</button>
                    <button class="alphabet-btn" data-letter="T">T</button>
                    <button class="alphabet-btn" data-letter="U">U</button>
                    <button class="alphabet-btn" data-letter="V">V</button>
                    <button class="alphabet-btn" data-letter="W">W</button>
                    <button class="alphabet-btn" data-letter="X">X</button>
                    <button class="alphabet-btn" data-letter="Y">Y</button>
                    <button class="alphabet-btn" data-letter="Z">Z</button>
                </div>
                <button class="alphabet-clear">
                    <i class="fas fa-times"></i>
                    <span>清除</span>
                </button>
            </div>
        </aside>

        <!-- 统计概览 -->
        <section class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow p-4 flex items-center">
                <div class="bg-blue-100 p-3 rounded-full mr-4">
                    <i class="fa fa-users text-primary text-xl"></i>
                </div>
                <div>
                    <p class="text-neutral text-sm">总学生数</p>
                    <p id="totalStudents" class="text-2xl font-bold">0</p>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow p-4 flex items-center">
                <div class="bg-yellow-100 p-3 rounded-full mr-4">
                    <i class="fa fa-sun-o text-sun text-xl"></i>
                </div>
                <div>
                    <p class="text-neutral text-sm">平均等级</p>
                    <p id="averageRating" class="text-2xl font-bold">0</p>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow p-4 flex items-center">
                <div class="bg-yellow-100 p-3 rounded-full mr-4">
                    <i class="fa fa-trophy text-trophy text-xl"></i>
                </div>
                <div>
                    <p class="text-neutral text-sm">最高等级</p>
                    <p id="highestRating" class="text-2xl font-bold">0</p>
                </div>
            </div>
        </section>

        <!-- 等级说明 -->
        <section class="bg-white rounded-xl shadow p-4 mb-6">
            <div class="flex flex-wrap items-center gap-4 justify-center">
                <div class="flex items-center">
                    <i class="fa fa-star text-star text-xl mr-2"></i>
                    <span class="text-gray-700">星星</span>
                </div>
                <div class="text-neutral">5 = 1</div>
                <div class="flex items-center">
                    <i class="fa fa-moon-o text-moon text-xl mr-2"></i>
                    <span class="text-gray-700">月亮</span>
                </div>
                <div class="text-neutral">5 = 1</div>
                <div class="flex items-center">
                    <i class="fa fa-sun-o text-sun text-xl mr-2"></i>
                    <span class="text-gray-700">太阳</span>
                </div>
                <div class="mx-2 h-4 border-r border-gray-300"></div>
                <div class="flex items-center">
                    <i class="fa fa-trophy text-trophy text-xl mr-2 trophy-shine"></i>
                    <span class="text-gray-700">积分最高的学生</span>
                </div>
            </div>
        </section>

        <!-- 搜索和筛选 -->
        <section class="bg-white rounded-xl shadow p-4 mb-6">
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-1">
                    <div class="relative">
                        <input type="text" id="searchInput" placeholder="搜索学生姓名、班级或首字母（如：张 或 z 或 张同学）"
                            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                <div class="flex gap-2 flex-wrap">
                    <button id="filterAll"
                        class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-all">
                        全部学生
                    </button>
                    <button id="filterHighRank"
                        class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-all">
                        高等级学生
                    </button>
                </div>
            </div>
        </section>

        <!-- 学生列表 -->
        <section class="mb-16 md:mb-6">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">学生列表</h2>
                <p id="studentCount" class="text-neutral">显示 0 名学生</p>
            </div>

            <div id="studentList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <!-- 学生卡片将通过JS动态生成 -->
                <div class="col-span-full text-center py-12 text-neutral">
                    <i class="fa fa-folder-open-o text-4xl mb-3"></i>
                    <p>暂无学生数据，请添加学生</p>
                </div>
            </div>
        </section>
    </main>

    <!-- 移动端底部导航栏 -->
    <div class="mobile-nav md:hidden">
        <div class="mobile-nav-grid">
            <!-- 作业 -->
            <button class="mobile-nav-item">
                <i class="mobile-nav-icon fas fa-book-open"></i>
                <span class="mobile-nav-label">作业</span>
            </button>

            <!-- 抽奖 -->
            <button class="mobile-nav-item">
                <i class="mobile-nav-icon fas fa-gift"></i>
                <span class="mobile-nav-label">抽奖</span>
            </button>

            <!-- 点名 -->
            <button class="mobile-nav-item active" id="mobileRandomCallBtn">
                <i class="mobile-nav-icon fas fa-random"></i>
                <span class="mobile-nav-label">点名</span>
            </button>

            <!-- 数据 -->
            <button class="mobile-nav-item">
                <i class="mobile-nav-icon fas fa-database"></i>
                <span class="mobile-nav-label">数据</span>
            </button>

            <!-- 添加 -->
            <button class="mobile-nav-item" id="mobileAddBtn">
                <i class="mobile-nav-icon fas fa-plus"></i>
                <span class="mobile-nav-label">添加</span>
            </button>
        </div>
    </div>

    <!-- 随机点名结果模态框 -->
    <div id="randomCallModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 overflow-hidden">
            <div class="p-6 bg-accent text-white text-center">
                <h3 class="text-2xl font-bold">随机点名</h3>
                <p class="mt-1 opacity-90" id="callStatusText">正在随机选择...</p>
            </div>
            <div class="p-8 text-center">
                <div id="selectedStudentAvatar"
                    class="w-24 h-24 bg-accent/10 rounded-full flex items-center justify-center mx-auto mb-4 scale-in">
                    <i class="fa fa-user text-4xl text-accent"></i>
                </div>

                <!-- 滚动区域 -->
                <div class="h-20 overflow-hidden mb-2 relative">
                    <div id="nameScrollContainer" class="absolute w-full">
                        <h4 id="selectedStudentName" class="text-3xl font-bold text-gray-800 my-4">张三</h4>
                    </div>
                </div>

                <p id="selectedStudentClass" class="text-xl text-neutral mb-4">三年级二班</p>
                <div id="selectedStudentRating" class="flex justify-center gap-1 mb-6 flex-wrap">
                    <!-- 等级图标将通过JS动态生成 -->
                </div>

                <div id="callActionButtons" class="flex gap-3 hidden">
                    <button id="closeRandomCall"
                        class="flex-1 bg-gray-200 text-gray-700 py-3 rounded-lg hover:bg-gray-300 transition-all text-lg">
                        关闭
                    </button>
                    <button id="operateSelectedStudent"
                        class="flex-1 bg-primary text-white py-3 rounded-lg hover:bg-primary/90 transition-all text-lg">
                        等级操作
                    </button>
                </div>

                <!-- 加载动画 -->
                <div id="callLoadingIndicator" class="flex justify-center">
                    <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-accent"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加学生模态框 - 增加头像上传功能 -->
    <div id="addStudentModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-xl font-bold text-gray-800">添加新学生</h3>
            </div>
            <div class="p-6">
                <form id="addStudentForm">
                    <!-- 头像上传区域 -->
                    <div class="mb-6 text-center">
                        <div
                            class="avatar-upload mx-auto w-28 h-28 bg-gray-100 rounded-full flex items-center justify-center overflow-hidden border-2 border-dashed border-gray-300 hover:border-primary transition-colors">
                            <img id="addAvatarPreview" src="" alt="学生头像预览" class="w-full h-full object-cover hidden">
                            <div id="addAvatarPlaceholder"
                                class="flex flex-col items-center justify-center text-gray-400">
                                <i class="fa fa-user text-4xl mb-2"></i>
                                <p class="text-xs">点击上传头像</p>
                            </div>
                            <input type="file" id="addAvatarInput" accept="image/*" class="hidden">
                        </div>
                        <p class="text-xs text-neutral mt-2">支持JPG、PNG格式，建议尺寸200x200px</p>
                    </div>

                    <div class="mb-4">
                        <label for="studentName" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                        <input type="text" id="studentName" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    <div class="mb-4">
                        <label for="studentClass" class="block text-sm font-medium text-gray-700 mb-1">班级</label>
                        <input type="text" id="studentClass" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    <div class="mb-6">
                        <label for="initialStars" class="block text-sm font-medium text-gray-700 mb-1">初始星星数</label>
                        <input type="number" id="initialStars" value="0" min="0"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    <div class="flex gap-3">
                        <button type="button" id="cancelAdd"
                            class="flex-1 bg-gray-200 text-gray-700 py-2 rounded-lg hover:bg-gray-300 transition-all">
                            取消
                        </button>
                        <button type="submit"
                            class="flex-1 bg-primary text-white py-2 rounded-lg hover:bg-primary/90 transition-all">
                            添加
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 批量添加学生模态框 -->
    <div id="batchAddStudentModal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-xl font-bold text-gray-800">批量添加学生</h3>
            </div>
            <div class="p-6">
                <form id="batchAddStudentForm">
                    <div class="mb-4">
                        <label for="batchStudentNames"
                            class="block text-sm font-medium text-gray-700 mb-1">学生姓名（用逗号分隔）</label>
                        <textarea id="batchStudentNames" rows="4" required placeholder="例如：张三,李四,王五,赵六"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary/50"></textarea>
                        <p class="text-xs text-neutral mt-1">请输入学生姓名，用英文或中文逗号分隔</p>
                    </div>
                    <div class="mb-4">
                        <label for="batchStudentClass"
                            class="block text-sm font-medium text-gray-700 mb-1">班级（将应用于所有学生）</label>
                        <input type="text" id="batchStudentClass" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary/50">
                    </div>
                    <div class="mb-6">
                        <label for="batchInitialStars"
                            class="block text-sm font-medium text-gray-700 mb-1">初始星星数（将应用于所有学生）</label>
                        <input type="number" id="batchInitialStars" value="0" min="0"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary/50">
                    </div>
                    <div class="flex gap-3">
                        <button type="button" id="cancelBatchAdd"
                            class="flex-1 bg-gray-200 text-gray-700 py-2 rounded-lg hover:bg-gray-300 transition-all">
                            取消
                        </button>
                        <button type="submit"
                            class="flex-1 bg-secondary text-white py-2 rounded-lg hover:bg-secondary/90 transition-all">
                            批量添加
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 等级操作模态框 - 增加头像显示 -->
    <div id="ratingModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-xl font-bold text-gray-800">调整星星</h3>
                <div class="flex items-center mt-3">
                    <div id="ratingModalAvatar" class="w-12 h-12 rounded-full overflow-hidden mr-3">
                        <i class="fa fa-user text-2xl text-gray-400"></i>
                    </div>
                    <div>
                        <p id="currentStudentName" class="text-neutral">学生：张三</p>
                        <div id="currentStudentRating" class="flex gap-1 mt-1">
                            <!-- 等级图标将通过JS动态生成 -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="p-6">
                <form id="ratingForm">
                    <input type="hidden" id="studentId">
                    <div class="mb-4">
                        <label for="starsChange" class="block text-sm font-medium text-gray-700 mb-1">星星变动值</label>
                        <div class="flex">
                            <button type="button" id="decreaseBtn"
                                class="bg-gray-200 px-4 py-2 border border-r-0 border-gray-300 rounded-l-lg hover:bg-gray-300 transition-all">
                                <i class="fa fa-minus"></i>
                            </button>
                            <input type="number" id="starsChange" value="1" min="1"
                                class="flex-1 px-4 py-2 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 text-center">
                            <button type="button" id="increaseBtn"
                                class="bg-gray-200 px-4 py-2 border border-l-0 border-gray-300 rounded-r-lg hover:bg-gray-300 transition-all">
                                <i class="fa fa-plus"></i>
                            </button>
                        </div>
                        <p class="text-xs text-neutral mt-1">输入正数，通过加减按钮选择操作类型</p>
                    </div>
                    <!-- <div class="mb-6">
                        <label for="changeReason" class="block text-sm font-medium text-gray-700 mb-1">变动原因</label>
                        <input type="text" id="changeReason" placeholder="例如：作业完成优秀"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div> -->
                    <div class="flex gap-3">
                        <button type="button" id="cancelRating"
                            class="flex-1 bg-gray-200 text-gray-700 py-2 rounded-lg hover:bg-gray-300 transition-all">
                            取消
                        </button>
                        <div class="flex-1 grid grid-cols-2 gap-2">
                            <button type="submit" name="operation" value="subtract"
                                class="bg-danger text-white py-2 rounded-lg hover:bg-danger/90 transition-all">
                                扣除
                            </button>
                            <button type="submit" name="operation" value="add"
                                class="bg-secondary text-white py-2 rounded-lg hover:bg-secondary/90 transition-all">
                                增加
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 其他模态框保持不变 -->
    <div id="importConfirmModal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-xl font-bold text-gray-800 flex items-center">
                    <i class="fa fa-exclamation-triangle text-accent mr-2"></i>
                    确认导入数据
                </h3>
            </div>
            <div class="p-6">
                <p class="mb-4 text-gray-700">导入数据将覆盖当前所有学生信息，是否继续？</p>
                <p class="text-sm text-neutral mb-6">请确保导入的是正确的学生数据备份文件</p>
                <div class="flex gap-3">
                    <button id="cancelImport"
                        class="flex-1 bg-gray-200 text-gray-700 py-2 rounded-lg hover:bg-gray-300 transition-all">
                        取消
                    </button>
                    <button id="confirmImport"
                        class="flex-1 bg-primary text-white py-2 rounded-lg hover:bg-primary/90 transition-all">
                        确认导入
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div id="clearDataConfirmModal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-xl font-bold text-gray-800 flex items-center">
                    <i class="fa fa-exclamation-circle text-danger mr-2"></i>
                    确认清空数据
                </h3>
            </div>
            <div class="p-6">
                <p class="mb-4 text-gray-700">此操作将删除所有学生数据，且无法恢复，是否继续？</p>
                <div class="flex gap-3">
                    <button id="cancelClearData"
                        class="flex-1 bg-gray-200 text-gray-700 py-2 rounded-lg hover:bg-gray-300 transition-all">
                        取消
                    </button>
                    <button id="confirmClearData"
                        class="flex-1 bg-danger text-white py-2 rounded-lg hover:bg-danger/90 transition-all">
                        确认清空
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知提示 -->
    <div id="notification"
        class="fixed top-4 right-4 px-4 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300 flex items-center z-50 hidden">
        <i id="notificationIcon" class="mr-2"></i>
        <span id="notificationMessage"></span>
    </div>

    <!-- 背景音乐 - 随机点名专用 -->
    <audio id="randomCallMusic" preload="auto" loop>
        <source src="./mp3/suiji.m4a" type="audio/mp4">
    </audio>


    <script>
        // 学生等级管理 - 增加头像功能
        class StudentManager {
            constructor() {
                this.students = this.loadFromLocalStorage();
                this.currentFilter = 'all';
                this.importedData = null;
                this.selectedStudentId = null;
                this.animationFrameId = null;
                this.topStudentsCount = 3; // 显示奖杯的顶尖学生数量
                this.initEventListeners();
                this.renderStudentList();
                this.updateStatistics();
                // 音频控制
                this.backgroundMusic = null;
                this.initBackgroundMusic();
                this.initAlphabetIndex();
            }

            // 初始化背景音乐
            initBackgroundMusic() {
                this.backgroundMusic = document.getElementById('randomCallMusic');
                if (this.backgroundMusic) {
                    // 设置音量（0-1之间）
                    this.backgroundMusic.volume = 0.8;
                    // 预加载音频
                    this.backgroundMusic.load();
                }
            }

            // 播放背景音乐
            playBackgroundMusic() {
                if (this.backgroundMusic) {
                    this.backgroundMusic.currentTime = 3; // 从第2秒开始播放
                    this.backgroundMusic.play().catch(error => {
                        console.log('背景音乐播放失败:', error);
                    });
                }
            }

            // 停止背景音乐
            stopBackgroundMusic() {
                if (this.backgroundMusic) {
                    this.backgroundMusic.pause();
                    this.backgroundMusic.currentTime = 0;
                }
            }

            // 从localStorage加载数据
            loadFromLocalStorage() {
                const data = localStorage.getItem('studentRatings');
                return data ? JSON.parse(data) : [];
            }

            // 保存数据到localStorage
            saveToLocalStorage() {
                localStorage.setItem('studentRatings', JSON.stringify(this.students));
            }

            // 计算等级（太阳、月亮、星星）
            calculateRating(stars) {
                const totalStars = Math.max(0, stars);
                const suns = Math.floor(totalStars / 25); // 5星星=1月亮，5月亮=1太阳 → 25星星=1太阳
                const remainingAfterSuns = totalStars % 25;
                const moons = Math.floor(remainingAfterSuns / 5);
                const remainingStars = remainingAfterSuns % 5;

                return {
                    suns,
                    moons,
                    stars: remainingStars,
                    totalStars
                };
            }

            // 生成等级图标HTML
            generateRatingHtml(rating, withAnimation = false) {
                const sunsHtml = Array(rating.suns).fill().map((_, i) =>
                    `<i class="fa fa-sun-o text-sun text-xl ${withAnimation ? 'shine' : ''}" style="animation-delay: ${i * 0.2}s"></i>`
                ).join('');

                const moonsHtml = Array(rating.moons).fill().map((_, i) =>
                    `<i class="fa fa-moon-o text-moon text-xl ${withAnimation ? 'shine' : ''}" style="animation-delay: ${(rating.suns + i) * 0.2}s"></i>`
                ).join('');

                const starsHtml = Array(rating.stars).fill().map((_, i) =>
                    `<i class="fa fa-star text-star text-xl ${withAnimation ? 'shine' : ''}" style="animation-delay: ${(rating.suns + rating.moons + i) * 0.2}s"></i>`
                ).join('');

                return `${sunsHtml}${moonsHtml}${starsHtml}`;
            }

            // 获取顶尖学生ID列表
            getTopStudentsIds() {
                if (this.students.length <= this.topStudentsCount) {
                    // 如果学生数量少于等于顶尖数量，返回所有学生ID
                    return this.students
                        .sort((a, b) => b.stars - a.stars)
                        .map(student => student.id);
                }

                // 按星星数量降序排序并取前几名
                return this.students
                    .sort((a, b) => b.stars - a.stars)
                    .slice(0, this.topStudentsCount)
                    .map(student => student.id);
            }

            // 获取排名徽章样式
            getRankBadgeStyle(rank) {
                if (rank === 1) return 'bg-gold';
                if (rank === 2) return 'bg-silver text-gray-700';
                if (rank === 3) return 'bg-bronze';
                return 'bg-gray-500';
            }

            // 生成奖杯HTML（前三名依次递减）
            generateTrophyHtml(rank) {
                if (!rank || rank < 1 || rank > 3) return '';

                let trophyColor = 'text-gold';
                let trophyCount = 3;

                if (rank === 2) {
                    trophyColor = 'text-silver';
                    trophyCount = 2;
                } else if (rank === 3) {
                    trophyColor = 'text-bronze';
                    trophyCount = 1;
                }

                return Array(trophyCount)
                    .fill()
                    .map((_, i) => `<i class="fa fa-trophy ${trophyColor} trophy-shine" style="animation-delay: ${i * 0.2}s"></i>`)
                    .join('');
            }

            // 添加新学生 - 增加头像参数
            addStudent(name, className, stars = 0, avatar = null) {
                const student = {
                    id: Date.now().toString(),
                    name: name,
                    className: className,
                    stars: parseInt(stars) || 0,
                    avatar: avatar,
                    createdAt: new Date().toISOString(),
                    history: []
                };

                this.students.push(student);
                this.saveToLocalStorage();
                this.renderStudentList();
                this.updateStatistics();

                // 添加成功动画
                setTimeout(() => {
                    const studentElement = document.querySelector(`[data-student-id="${student.id}"]`);
                    if (studentElement) {
                        this.showSuccessEffect(studentElement);
                    }
                }, 100);

                return student;
            }

            // 批量添加学生
            batchAddStudents(names, className, stars = 0) {
                // 处理逗号分隔的姓名，支持中英文逗号
                const nameList = names.split(/[,，]/)
                    .map(name => name.trim())
                    .filter(name => name.length > 0); // 过滤空字符串

                if (nameList.length === 0) {
                    return 0;
                }

                // 批量添加学生，无头像
                nameList.forEach(name => {
                    this.addStudent(name, className, stars);
                });

                this.saveToLocalStorage();
                this.renderStudentList();
                this.updateStatistics();

                return nameList.length;
            }

            // 更新学生星星数量
            updateStars(studentId, change, isAdd = true) {
                const student = this.students.find(s => s.id === studentId);
                if (!student) return false;

                const changeValue = parseInt(change);
                if (isAdd) {
                    student.stars += changeValue;
                } else {
                    student.stars = Math.max(0, student.stars - changeValue);
                }


                // 记录操作历史
                // student.history.unshift({
                //     type: isAdd ? 'add' : 'subtract',
                //     amount: change,
                //     oldValue: oldStars,
                //     newValue: newStars,
                //     timestamp: new Date().toISOString()
                // });

                this.saveToLocalStorage();
                this.renderStudentList();
                this.updateStatistics();

                // 获取学生卡片元素并滚动到视图
                setTimeout(() => {
                    const studentCard = document.querySelector(`[data-student-id="${studentId}"]`);
                    if (studentCard) {
                        studentCard.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center'
                        });

                        // 高亮显示
                        studentCard.style.transform = 'scale(1.05)';
                        studentCard.style.transition = 'transform 0.3s ease';
                        setTimeout(() => {
                            studentCard.style.transform = 'scale(1)';
                        }, 300);

                        // 显示成功特效
                        if (isAdd) {
                            this.showSuccessEffect(studentCard);
                        }
                    }
                }, 100);

                return true;
            }

            // 更新学生头像
            updateAvatar(studentId, avatarData) {
                const student = this.students.find(s => s.id === studentId);
                if (!student) return false;

                student.avatar = avatarData;
                this.saveToLocalStorage();
                this.renderStudentList();
                return true;
            }

            // 删除学生
            deleteStudent(studentId) {
                this.students = this.students.filter(s => s.id !== studentId);
                this.saveToLocalStorage();
                this.renderStudentList();
                this.updateStatistics();
            }

            // 随机选择一名学生
            randomSelectStudent() {
                if (this.students.length === 0) {
                    this.showNotification('没有学生数据，无法进行随机点名', 'warning');
                    return null;
                }

                const randomIndex = Math.floor(Math.random() * this.students.length);
                const selectedStudent = this.students[randomIndex];
                this.selectedStudentId = selectedStudent.id;

                return selectedStudent;
            }

            // 执行随机点名动画效果
            performRandomCallAnimation() {
                if (this.students.length < 2) {
                    // 学生太少时，直接显示结果
                    const selected = this.randomSelectStudent();
                    if (selected) {
                        this.showCallResult(selected);
                    }
                    return;
                }

                // 显示模态框
                const modal = document.getElementById('randomCallModal');
                modal.classList.remove('hidden');

                // 播放背景音乐
                this.playBackgroundMusic();

                // 重置UI状态
                document.getElementById('callStatusText').textContent = '正在随机选择...';

                document.getElementById('callLoadingIndicator').classList.remove('hidden');
                document.getElementById('callActionButtons').classList.add('hidden');

                const nameElement = document.getElementById('selectedStudentName');
                const classElement = document.getElementById('selectedStudentClass');
                const ratingElement = document.getElementById('selectedStudentRating');
                const scrollContainer = document.getElementById('nameScrollContainer');
                const avatarElement = document.getElementById('selectedStudentAvatar');

                // 重置动画状态
                scrollContainer.classList.remove('name-scroll', 'slow-down');
                nameElement.textContent = '';
                classElement.textContent = '';
                ratingElement.innerHTML = '';
                avatarElement.innerHTML = '<img src="images/student.png" alt="默认头像" class="w-full h-full object-cover rounded-full">';

                // 准备动画
                let startTime = null;
                const duration = 3000; // 动画总时长3秒
                let lastUpdateTime = 0;
                let updateInterval = 80; // 初始更新间隔（毫秒）

                // 动画函数 - 模拟随机滚动效果
                const animate = (timestamp) => {
                    if (!startTime) startTime = timestamp;
                    const elapsed = timestamp - startTime;

                    // 计算进度（0-1）
                    const progress = Math.min(elapsed / duration, 1);

                    // 逐渐减慢滚动速度
                    if (timestamp - lastUpdateTime > updateInterval) {
                        lastUpdateTime = timestamp;

                        // 随机选择一个学生显示
                        const randomIndex = Math.floor(Math.random() * this.students.length);
                        const randomStudent = this.students[randomIndex];

                        nameElement.textContent = randomStudent.name;
                        classElement.textContent = randomStudent.className;

                        // 更新头像
                        if (randomStudent.avatar) {
                            avatarElement.innerHTML = `<img src="${randomStudent.avatar}" alt="${randomStudent.name}的头像" class="w-full h-full object-cover rounded-full">`;
                        } else {
                            avatarElement.innerHTML = '<img src="images/student.png" alt="默认头像" class="w-full h-full object-cover rounded-full">';
                        }

                        // 计算并显示随机学生的等级
                        const rating = this.calculateRating(randomStudent.stars);
                        ratingElement.innerHTML = this.generateRatingHtml(rating);

                        // 随时间增加更新间隔，创造减速效果
                        updateInterval = 80 + (progress * 400);
                    }

                    // 动画未结束，继续
                    if (progress < 1) {
                        this.animationFrameId = requestAnimationFrame(animate);
                    } else {
                        // 动画结束，显示最终选中的学生
                        const selected = this.randomSelectStudent();
                        if (selected) {
                            this.showCallResult(selected);
                        }
                    }
                };

                // 开始动画
                this.animationFrameId = requestAnimationFrame(animate);
            }

            // 显示点名结果
            showCallResult(student) {
                // 停止背景音乐
                this.stopBackgroundMusic();

                // 更新显示内容
                document.getElementById('selectedStudentName').textContent = student.name;
                document.getElementById('selectedStudentClass').textContent = student.className;
                document.getElementById('callStatusText').textContent = '点名结果';

                // 更新头像
                const avatarElement = document.getElementById('selectedStudentAvatar');
                if (student.avatar) {
                    avatarElement.innerHTML = `<img src="${student.avatar}" alt="${student.name}的头像" class="w-full h-full object-cover rounded-full">`;
                } else {
                    avatarElement.innerHTML = '<img src="images/student.png" alt="默认头像" class="w-full h-full object-cover rounded-full">';
                }

                // 计算并显示选中学生的等级，带动画效果
                const rating = this.calculateRating(student.stars);
                document.getElementById('selectedStudentRating').innerHTML = this.generateRatingHtml(rating, true);

                // 隐藏加载指示器，显示操作按钮
                document.getElementById('callLoadingIndicator').classList.add('hidden');
                document.getElementById('callActionButtons').classList.remove('hidden');

                // 添加最终选中动画
                avatarElement.classList.remove('spin-in', 'pulse');
                void avatarElement.offsetWidth; // 触发重绘
                avatarElement.classList.add('spin-in', 'pulse');

                const nameEl = document.getElementById('selectedStudentName');
                nameEl.classList.remove('bounce-in');
                void nameEl.offsetWidth; // 触发重绘
                nameEl.classList.add('bounce-in');
            }

            // 搜索学生
            searchStudents(keyword) {
                if (!keyword) return this.applyFilter();

                const lowerKeyword = keyword.toLowerCase().trim();

                // 分割多个关键字（支持空格分隔）
                const keywords = lowerKeyword.split(/\s+/).filter(k => k.length > 0);

                return this.students.filter(student => {
                    const name = student.name.toLowerCase();
                    const className = student.className.toLowerCase();

                    // 检查是否匹配所有关键字
                    return keywords.every(kw => {
                        // 完全匹配
                        if (name.includes(kw) || className.includes(kw)) {
                            return true;
                        }

                        // 首字母匹配
                        if (kw.length === 1) {
                            return name.startsWith(kw) || this.getPinyinInitial(name) === kw;
                        }

                        // 拼音首字母匹配（简单实现）
                        const pinyinInitial = this.getPinyinInitial(name);
                        return pinyinInitial && pinyinInitial.startsWith(kw);
                    });
                });
            }

            // 获取中文姓名的拼音首字母（简单实现）
            getPinyinInitial(name) {
                // 常见中文姓氏拼音映射
                const pinyinMap = {
                    '张': 'z', '王': 'w', '李': 'l', '赵': 'z', '刘': 'l',
                    '陈': 'c', '杨': 'y', '黄': 'h', '周': 'z', '吴': 'w',
                    '徐': 'x', '孙': 's', '胡': 'h', '朱': 'z', '高': 'g',
                    '林': 'l', '何': 'h', '郭': 'g', '马': 'm', '罗': 'l',
                    '梁': 'l', '宋': 's', '郑': 'z', '谢': 'x', '韩': 'h',
                    '唐': 't', '冯': 'f', '于': 'y', '董': 'd', '萧': 'x',
                    '程': 'c', '曹': 'c', '袁': 'y', '邓': 'd', '许': 'x',
                    '傅': 'f', '沈': 's', '曾': 'z', '彭': 'p', '吕': 'l',
                    '苏': 's', '卢': 'l', '蒋': 'j', '蔡': 'c', '贾': 'j',
                    '丁': 'd', '魏': 'w', '薛': 'x', '叶': 'y', '阎': 'y',
                    '余': 'y', '潘': 'p', '杜': 'd', '戴': 'd', '夏': 'x',
                    '钟': 'z', '汪': 'w', '田': 't', '任': 'r', '姜': 'j',
                    '范': 'f', '方': 'f', '石': 's', '姚': 'y', '谭': 't',
                    '廖': 'l', '邹': 'z', '熊': 'x', '金': 'j', '陆': 'l',
                    '郝': 'h', '孔': 'k', '白': 'b', '崔': 'c', '康': 'k',
                    '毛': 'm', '邱': 'q', '秦': 'q', '江': 'j', '史': 's',
                    '顾': 'g', '侯': 'h', '邵': 's', '孟': 'm', '龙': 'l',
                    '万': 'w', '段': 'd', '雷': 'l', '钱': 'q', '汤': 't',
                    '尹': 'y', '黎': 'l', '易': 'y', '常': 'c', '武': 'w',
                    '乔': 'q', '贺': 'h', '赖': 'l', '龚': 'g', '文': 'w',
                    '隋': 's', '柳': 'l', '辛': 'x', '候': 'h', '栾': 'l',
                    '朴': 'p', '戚': 'q', '俞': 'y', '邴': 'b', '齐': 'q',
                    '栗': 'l', '安': 'a', '宫': 'g',
                };

                // 获取首字符的拼音首字母
                const firstChar = name.charAt(0);
                if (pinyinMap[firstChar]) {
                    return pinyinMap[firstChar];
                }

                // 如果是英文字母，直接返回
                if (/[a-zA-Z]/.test(firstChar)) {
                    return firstChar.toLowerCase();
                }

                // 返回null表示无法获取拼音首字母
                return null;
            }

            // 应用筛选
            applyFilter() {
                if (this.currentFilter === 'high') {
                    // 高等级学生：星星数高于平均值
                    const average = this.calculateAverageStars();
                    return this.students.filter(s => s.stars > average);
                }
                return [...this.students];
            }

            // 计算平均星星数
            calculateAverageStars() {
                if (this.students.length === 0) return 0;
                const total = this.students.reduce((sum, student) => sum + student.stars, 0);
                return Math.round(total / this.students.length);
            }

            // 获取最高星星数
            getHighestStars() {
                if (this.students.length === 0) return 0;
                return Math.max(...this.students.map(s => s.stars));
            }

            // 格式化星星数为等级显示文本
            formatRatingText(stars) {
                const rating = this.calculateRating(stars);
                let text = '';
                if (rating.suns > 0) text += `${rating.suns}太阳 `;
                if (rating.moons > 0) text += `${rating.moons}月亮 `;
                text += `${rating.stars}星星`;
                return text;
            }

            // 更新统计信息
            updateStatistics() {
                document.getElementById('totalStudents').textContent = this.students.length;

                const averageStars = this.calculateAverageStars();
                document.getElementById('averageRating').textContent = this.formatRatingText(averageStars);

                const highestStars = this.getHighestStars();
                document.getElementById('highestRating').textContent = this.formatRatingText(highestStars);

                document.getElementById('studentCount').textContent = `显示 ${this.searchStudents(document.getElementById('searchInput').value).length} 名学生`;
            }

            // 渲染学生列表 - 增加头像显示并优化居中对齐和字号
            renderStudentList() {
                const studentList = document.getElementById('studentList');
                const searchTerm = document.getElementById('searchInput').value;
                let filteredStudents = this.searchStudents(searchTerm);

                // 获取前三名学生并排序
                const topStudents = [...this.students]
                    .sort((a, b) => b.stars - a.stars || new Date(a.createdAt) - new Date(b.createdAt))
                    .slice(0, this.topStudentsCount);
                const topStudentsIds = topStudents.map(s => s.id);

                if (filteredStudents.length === 0) {
                    studentList.innerHTML = `
                        <div class="col-span-full text-center py-12 text-neutral">
                            <i class="fa fa-folder-open-o text-4xl mb-3"></i>
                            <p>暂无学生数据，请添加学生</p>
                        </div>
                    `;
                    return;
                }

                // 对筛选后的学生进行排序
                const sortedStudents = [...filteredStudents].sort((a, b) =>
                    b.stars - a.stars
                );

                studentList.innerHTML = sortedStudents.map(student => {
                    const rating = this.calculateRating(student.stars);
                    // 确定学生排名（仅前三名有排名）
                    const rank = topStudentsIds.indexOf(student.id) + 1;

                    // 生成奖杯HTML
                    const trophyHtml = this.generateTrophyHtml(rank);

                    // 生成排名徽章（仅前三名显示）
                    const rankBadgeHtml = rank
                        ? `<div class="rank-badge ${this.getRankBadgeStyle(rank)}">${rank}</div>`
                        : '';

                    // 生成头像HTML
                    const avatarHtml = student.avatar
                        ? `<img src="${student.avatar}" alt="${student.name}的头像" class="w-full h-full object-cover rounded-full">`
                        : `<img src="images/student.png" alt="默认头像" class="w-full h-full object-cover rounded-full">`;

                    return `
                      <div class="bg-white rounded-xl shadow-md hover:shadow-lg transition-all duration-300 p-4 relative card-hover" data-student-id="${student.id}">
                        ${rankBadgeHtml}
                        
                        <!-- 右上角操作按钮 -->
                        <div class="absolute top-4 right-4 flex gap-1">
                            <!-- <button class="editRatingBtn text-primary p-2 hover:bg-blue-50 rounded-full transition-all" 
                                data-id="${student.id}" title="编辑等级">
                                <i class="fa fa-pencil"></i>
                            </button> -->
                            <button class="deleteStudentBtn text-danger p-2 hover:bg-red-50 rounded-full transition-all" 
                                data-id="${student.id}" title="删除学生">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                        
                        <!-- 学生基本信息区域 - 居中对齐并增大字号 -->
                        <div class="flex justify-center items-center mb-4">
                            <div class="w-14 h-14 rounded-full overflow-hidden mr-4 border-2 ${rank === 1 ? 'border-gold' :
                            rank === 2 ? 'border-silver' :
                                rank === 3 ? 'border-bronze' : 'border-gray-200'
                        }">
                                ${avatarHtml}
                            </div>
                            <h3 class="font-bold text-xl text-gray-800">${student.name}</h3>
                        </div>
                        
                        <!-- 班级信息 - 居中显示 -->
                        <div class="mb-2 text-center">
                            <p class="text-neutral text-base">班级: ${student.className}</p>
                        </div>
                        
                        <!-- 等级信息 - 居中显示并增大图标 -->
                        <div class="mb-4 text-center">
                            <p class="text-neutral text-sm mb-1">当前等级</p>
                            <div class="flex gap-1 mt-1 justify-center">
                                ${this.generateRatingHtml(rating)}
                            </div>
                            <p class="text-sm text-neutral mt-1">总计: ${student.stars} 星星</p>
                        </div>
                        
                        <!-- 奖杯显示 - 居中 -->
                        ${trophyHtml ? `<div class="flex justify-center gap-1 mb-4">${trophyHtml}</div>` : ''}
                        
                        <!-- 操作按钮区域 - 居中 -->
                        <div class="flex gap-2">
                            <button class="editAvatarBtn flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 py-2 rounded-lg text-sm transition-all"
                                data-id="${student.id}">
                                <i class="fa fa-picture-o mr-1"></i> 更换头像
                            </button>
                            <button class="quickAddBtn flex-1 bg-secondary/10 text-secondary px-3 py-2 rounded-lg text-sm hover:bg-secondary/20 transition-all"
                                data-id="${student.id}">
                                + 星星
                            </button>
                        </div>
                        
                    </div>
                    `;
                }).join('');

                this.bindStudentCardEvents();
            }

            // 格式化日期
            formatDate(dateString) {
                const date = new Date(dateString);
                return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
            }

            // 绑定学生卡片上的按钮事件 - 增加更换头像按钮事件
            bindStudentCardEvents() {
                // 编辑等级按钮事件
                document.querySelectorAll('.editRatingBtn, .quickAddBtn').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const studentId = e.currentTarget.dataset.id;
                        const student = this.students.find(s => s.id === studentId);

                        if (student) {
                            document.getElementById('studentId').value = studentId;
                            document.getElementById('currentStudentName').textContent = `学生：${student.name}`;

                            // 显示当前等级
                            const rating = this.calculateRating(student.stars);
                            document.getElementById('currentStudentRating').innerHTML = this.generateRatingHtml(rating);

                            // 显示头像
                            const avatarContainer = document.getElementById('ratingModalAvatar');
                            if (student.avatar) {
                                avatarContainer.innerHTML = `<img src="${student.avatar}" alt="${student.name}的头像" class="w-full h-full object-cover rounded-full">`;
                            } else {
                                avatarContainer.innerHTML = '<img src="images/student.png" alt="默认头像" class="w-full h-full object-cover rounded-full">';
                            }

                            document.getElementById('ratingModal').classList.remove('hidden');
                        }
                    });
                });

                // 删除学生按钮事件
                document.querySelectorAll('.deleteStudentBtn').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const studentId = e.currentTarget.dataset.id;
                        const student = this.students.find(s => s.id === studentId);

                        if (student && confirm(`确定要删除学生 ${student.name} 吗？`)) {
                            this.deleteStudent(studentId);
                            this.showNotification('学生已删除', 'warning');
                        }
                    });
                });

                // 更换头像按钮事件
                document.querySelectorAll('.editAvatarBtn').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const studentId = e.currentTarget.dataset.id;
                        const student = this.students.find(s => s.id === studentId);

                        if (student) {
                            // 创建一个临时的文件输入框
                            const input = document.createElement('input');
                            input.type = 'file';
                            input.accept = 'image/*';

                            input.onchange = (event) => {
                                const file = event.target.files[0];
                                if (!file) return;

                                // 检查文件类型
                                if (!file.type.startsWith('image/')) {
                                    this.showNotification('请选择图片文件', 'error');
                                    return;
                                }

                                const reader = new FileReader();
                                reader.onload = (e) => {
                                    // 更新头像
                                    this.updateAvatar(studentId, e.target.result);
                                    this.showNotification('头像已更新', 'success');
                                };
                                reader.readAsDataURL(file);
                            };

                            // 触发文件选择对话框
                            input.click();
                        }
                    });
                });
            }

            // 显示通知
            showNotification(message, type = 'success', showAnimation = false) {
                const notification = document.getElementById('notification');
                const icon = document.getElementById('notificationIcon');
                const messageEl = document.getElementById('notificationMessage');

                notification.className = 'fixed top-4 right-4 px-4 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300 flex items-center z-50';
                if (type === 'success') {
                    notification.classList.add('bg-green-600', 'text-white');
                    icon.className = 'fa fa-check-circle mr-2';
                } else if (type === 'error') {
                    notification.classList.add('bg-red-600', 'text-white');
                    icon.className = 'fa fa-exclamation-circle mr-2';
                } else if (type === 'warning') {
                    notification.classList.add('bg-orange-500', 'text-white');
                    icon.className = 'fa fa-exclamation-triangle mr-2';
                }

                messageEl.textContent = message;

                setTimeout(() => {
                    notification.classList.remove('translate-x-full');

                    // 如果是成功类型且需要动画，添加星星爆炸
                    if (type === 'success' && showAnimation) {
                        const rect = notification.getBoundingClientRect();
                        this.createStarExplosion(rect.left + rect.width / 2, rect.top + rect.height / 2);
                    }
                }, 100);

                setTimeout(() => {
                    notification.classList.add('translate-x-full');
                }, 3000);
            }

            // 导出数据 - 包含头像数据
            exportData() {
                if (this.students.length === 0) {
                    this.showNotification('没有数据可导出', 'warning');
                    return;
                }

                const exportData = {
                    students: this.students,
                    exportDate: new Date().toISOString(),
                    version: '1.1' // 版本号更新，标识包含头像功能
                };

                const jsonString = JSON.stringify(exportData, null, 2);
                const blob = new Blob([jsonString], { type: 'application/json' });

                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;

                const date = new Date();
                const fileName = `学生数据_${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}.json`;
                a.download = fileName;

                document.body.appendChild(a);
                a.click();

                setTimeout(() => {
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }, 0);

                this.showNotification('数据导出成功');
                document.getElementById('dataMenu').classList.add('hidden');
            }

            // 处理导入数据 - 支持包含头像的数据
            handleImportData(event) {
                const file = event.target.files[0];
                if (!file) return;

                if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
                    this.showNotification('请导入JSON格式的文件', 'error');
                    this.resetFileInput();
                    return;
                }

                const reader = new FileReader();

                reader.onload = (e) => {
                    try {
                        const importedData = JSON.parse(e.target.result);

                        if (!importedData.students || !Array.isArray(importedData.students)) {
                            throw new Error('数据格式不正确，缺少学生列表');
                        }

                        this.importedData = importedData.students;
                        document.getElementById('importConfirmModal').classList.remove('hidden');
                        document.getElementById('dataMenu').classList.add('hidden');

                    } catch (error) {
                        this.showNotification(`导入失败：${error.message}`, 'error');
                        console.error('导入数据错误:', error);
                    } finally {
                        this.resetFileInput();
                    }
                };

                reader.readAsText(file);
            }

            // 确认导入数据
            confirmImport() {
                if (!this.importedData) return;

                this.students = this.importedData;
                this.saveToLocalStorage();
                this.renderStudentList();
                this.updateStatistics();

                document.getElementById('importConfirmModal').classList.add('hidden');
                this.importedData = null;

                this.showNotification('数据导入成功');
            }

            // 清空所有数据
            clearAllData() {
                if (confirm('确定要清空所有学生数据吗？此操作不可恢复！')) {
                    this.students = [];
                    this.saveToLocalStorage();
                    this.renderStudentList();
                    this.updateStatistics();
                    document.getElementById('clearDataConfirmModal').classList.add('hidden');
                    this.showNotification('所有数据已清空', 'warning');
                    document.getElementById('dataMenu').classList.add('hidden');
                }
            }

            // 重置文件输入框
            resetFileInput() {
                const input = document.getElementById('importDataInput');
                input.value = '';
            }

            // 初始化事件监听器 - 增加头像上传相关事件
            initEventListeners() {
                // 批量添加学生相关事件
                document.getElementById('batchAddStudentBtn').addEventListener('click', () => {
                    document.getElementById('batchAddStudentModal').classList.remove('hidden');
                    document.getElementById('batchStudentNames').focus();
                });

                // document.getElementById('mobileBatchAddBtn').addEventListener('click', () => {
                //     document.getElementById('batchAddStudentModal').classList.remove('hidden');
                //     document.getElementById('batchStudentNames').focus();
                // });

                document.getElementById('cancelBatchAdd').addEventListener('click', () => {
                    document.getElementById('batchAddStudentModal').classList.add('hidden');
                    document.getElementById('batchAddStudentForm').reset();
                });

                document.getElementById('batchAddStudentForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    const names = document.getElementById('batchStudentNames').value.trim();
                    const className = document.getElementById('batchStudentClass').value.trim();
                    const stars = document.getElementById('batchInitialStars').value;

                    if (names && className) {
                        const count = this.batchAddStudents(names, className, stars);
                        if (count > 0) {
                            this.showNotification(`成功添加 ${count} 名学生`);
                            document.getElementById('batchAddStudentModal').classList.add('hidden');
                            document.getElementById('batchAddStudentForm').reset();
                        } else {
                            this.showNotification('未找到有效的学生姓名', 'error');
                        }
                    }
                });

                // 点击批量添加模态框外部关闭
                document.getElementById('batchAddStudentModal').addEventListener('click', (e) => {
                    if (e.target === document.getElementById('batchAddStudentModal')) {
                        document.getElementById('batchAddStudentModal').classList.add('hidden');
                        document.getElementById('batchAddStudentForm').reset();
                    }
                });

                // 数据管理下拉菜单交互
                const dataContainer = document.getElementById('dataManageContainer');
                const dataBtn = document.getElementById('dataManageBtn');
                const dataMenu = document.getElementById('dataMenu');

                dataBtn.addEventListener('click', () => {
                    dataMenu.classList.toggle('hidden');
                });

                dataContainer.addEventListener('mouseenter', () => {
                    dataMenu.classList.remove('hidden');
                });

                // 翻卡抽奖按钮事件
                document.getElementById('flipCardBtn').addEventListener('click', () => {
                    window.location.href = '抽奖.html';
                });

                // 随机点名按钮事件
                document.getElementById('randomCallBtn').addEventListener('click', () => {
                    this.performRandomCallAnimation();
                });

                // 移动端随机点名按钮
                document.getElementById('mobileRandomCallBtn').addEventListener('click', () => {
                    this.performRandomCallAnimation();
                });

                // 关闭随机点名模态框
                document.getElementById('closeRandomCall').addEventListener('click', () => {
                    // 取消可能正在进行的动画
                    if (this.animationFrameId) {
                        cancelAnimationFrame(this.animationFrameId);
                        this.animationFrameId = null;
                    }
                    document.getElementById('randomCallModal').classList.add('hidden');
                });

                // 对随机选中的学生进行等级操作
                document.getElementById('operateSelectedStudent').addEventListener('click', () => {
                    if (this.selectedStudentId) {
                        const student = this.students.find(s => s.id === this.selectedStudentId);
                        if (student) {
                            document.getElementById('studentId').value = this.selectedStudentId;
                            document.getElementById('currentStudentName').textContent = `学生：${student.name}`;

                            // 显示当前等级
                            const rating = this.calculateRating(student.stars);
                            document.getElementById('currentStudentRating').innerHTML = this.generateRatingHtml(rating);

                            // 显示头像
                            const avatarContainer = document.getElementById('ratingModalAvatar');
                            if (student.avatar) {
                                avatarContainer.innerHTML = `<img src="${student.avatar}" alt="${student.name}的头像" class="w-full h-full object-cover rounded-full">`;
                            } else {
                                avatarContainer.innerHTML = '<img src="images/student.png" alt="默认头像" class="w-full h-full object-cover rounded-full">';
                            }

                            document.getElementById('randomCallModal').classList.add('hidden');
                            document.getElementById('ratingModal').classList.remove('hidden');
                        }
                    }
                });

                // 点击随机点名模态框外部关闭
                document.getElementById('randomCallModal').addEventListener('click', (e) => {
                    if (e.target === document.getElementById('randomCallModal')) {
                        if (this.animationFrameId) {
                            cancelAnimationFrame(this.animationFrameId);
                            this.animationFrameId = null;
                        }
                        document.getElementById('randomCallModal').classList.add('hidden');
                    }
                });

                // 添加学生按钮
                document.getElementById('addStudentBtn').addEventListener('click', () => {
                    document.getElementById('addStudentModal').classList.remove('hidden');
                    document.getElementById('studentName').focus();

                    // 重置头像预览
                    const avatarPreview = document.getElementById('addAvatarPreview');
                    const avatarPlaceholder = document.getElementById('addAvatarPlaceholder');
                    avatarPreview.src = '';
                    avatarPreview.classList.add('hidden');
                    avatarPlaceholder.classList.remove('hidden');
                });

                // 移动端添加学生按钮
                document.getElementById('mobileAddBtn').addEventListener('click', () => {
                    document.getElementById('addStudentModal').classList.remove('hidden');
                    document.getElementById('studentName').focus();

                    // 重置头像预览
                    const avatarPreview = document.getElementById('addAvatarPreview');
                    const avatarPlaceholder = document.getElementById('addAvatarPlaceholder');
                    avatarPreview.src = '';
                    avatarPreview.classList.add('hidden');
                    avatarPlaceholder.classList.remove('hidden');
                });

                // 头像上传相关事件
                document.getElementById('addAvatarInput').addEventListener('change', (e) => {
                    const file = e.target.files[0];
                    if (!file) return;

                    // 检查文件类型
                    if (!file.type.startsWith('image/')) {
                        this.showNotification('请选择图片文件', 'error');
                        return;
                    }

                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const avatarPreview = document.getElementById('addAvatarPreview');
                        const avatarPlaceholder = document.getElementById('addAvatarPlaceholder');

                        avatarPreview.src = e.target.result;
                        avatarPreview.classList.remove('hidden');
                        avatarPlaceholder.classList.add('hidden');
                    };
                    reader.readAsDataURL(file);
                });

                // 点击头像上传区域触发文件选择
                document.querySelector('.avatar-upload').addEventListener('click', () => {
                    document.getElementById('addAvatarInput').click();
                });

                // 阻止头像上传区域的点击事件冒泡
                document.getElementById('addAvatarInput').addEventListener('click', (e) => {
                    e.stopPropagation();
                });

                // 取消添加学生
                document.getElementById('cancelAdd').addEventListener('click', () => {
                    document.getElementById('addStudentModal').classList.add('hidden');
                    document.getElementById('addStudentForm').reset();
                });

                // 提交添加学生表单 - 处理头像数据
                document.getElementById('addStudentForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    const name = document.getElementById('studentName').value.trim();
                    const className = document.getElementById('studentClass').value.trim();
                    const stars = document.getElementById('initialStars').value;

                    // 获取头像数据（如果有）
                    let avatar = null;
                    const avatarPreview = document.getElementById('addAvatarPreview');
                    if (!avatarPreview.classList.contains('hidden')) {
                        avatar = avatarPreview.src;
                    }

                    if (name && className) {
                        this.addStudent(name, className, stars, avatar);
                        this.saveToLocalStorage();
                        this.renderStudentList();
                        this.updateStatistics();
                        this.showNotification('学生添加成功');
                        document.getElementById('addStudentModal').classList.add('hidden');
                        document.getElementById('addStudentForm').reset();
                    }
                });

                // 取消等级操作
                document.getElementById('cancelRating').addEventListener('click', () => {
                    document.getElementById('ratingModal').classList.add('hidden');
                    document.getElementById('ratingForm').reset();
                });

                // 星星变动值增减按钮
                document.getElementById('increaseBtn').addEventListener('click', () => {
                    const input = document.getElementById('starsChange');
                    input.value = Math.max(1, parseInt(input.value) + 1);
                });

                document.getElementById('decreaseBtn').addEventListener('click', () => {
                    const input = document.getElementById('starsChange');
                    input.value = Math.max(1, parseInt(input.value) - 1);
                });

                // 提交等级操作表单
                document.getElementById('ratingForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    const studentId = document.getElementById('studentId').value;
                    const change = document.getElementById('starsChange').value;
                    // const reason = document.getElementById('changeReason').value.trim() || '无原因';
                    const isAdd = e.submitter.value === 'add';

                    if (studentId && change) {
                        const success = this.updateStars(studentId, change, isAdd);
                        if (success) {
                            this.showNotification(`星星已${isAdd ? '增加' : '扣除'}`);
                            document.getElementById('ratingModal').classList.add('hidden');
                            document.getElementById('ratingForm').reset();
                        }
                    }
                });

                // 搜索学生
                document.getElementById('searchInput').addEventListener('input', () => {
                    this.renderStudentList();
                });

                // 筛选按钮
                document.getElementById('filterAll').addEventListener('click', () => {
                    this.currentFilter = 'all';
                    document.getElementById('filterAll').className = 'bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-all';
                    document.getElementById('filterHighRank').className = 'bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-all';
                    this.renderStudentList();
                });

                document.getElementById('filterHighRank').addEventListener('click', () => {
                    this.currentFilter = 'high';
                    document.getElementById('filterAll').className = 'bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-all';
                    document.getElementById('filterHighRank').className = 'bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-all';
                    this.renderStudentList();
                });

                // 点击模态框外部关闭
                document.getElementById('addStudentModal').addEventListener('click', (e) => {
                    if (e.target === document.getElementById('addStudentModal')) {
                        document.getElementById('addStudentModal').classList.add('hidden');
                        document.getElementById('addStudentForm').reset();
                    }
                });

                document.getElementById('ratingModal').addEventListener('click', (e) => {
                    if (e.target === document.getElementById('ratingModal')) {
                        document.getElementById('ratingModal').classList.add('hidden');
                        document.getElementById('ratingForm').reset();
                    }
                });

                document.getElementById('importConfirmModal').addEventListener('click', (e) => {
                    if (e.target === document.getElementById('importConfirmModal')) {
                        document.getElementById('importConfirmModal').classList.add('hidden');
                        this.importedData = null;
                    }
                });

                document.getElementById('clearDataConfirmModal').addEventListener('click', (e) => {
                    if (e.target === document.getElementById('clearDataConfirmModal')) {
                        document.getElementById('clearDataConfirmModal').classList.add('hidden');
                    }
                });

                // 数据管理相关事件
                document.getElementById('exportDataBtn').addEventListener('click', () => {
                    this.exportData();
                });

                // 修复：改为监听文件输入框的change事件
                document.getElementById('importDataInput').addEventListener('change', (e) => {
                    this.handleImportData(e);
                });

                // 新增：点击导入菜单项时触发文件选择
                document.getElementById('importDataBtn').addEventListener('click', (e) => {
                    console.log(12321)
                    document.getElementById('importDataInput').click();
                });

                document.getElementById('clearDataBtn').addEventListener('click', () => {
                    if (this.students.length > 0) {
                        document.getElementById('clearDataConfirmModal').classList.remove('hidden');
                    } else {
                        this.showNotification('没有数据可清空', 'warning');
                    }
                });

                document.getElementById('confirmImport').addEventListener('click', () => {
                    this.confirmImport();
                });

                document.getElementById('cancelImport').addEventListener('click', () => {
                    document.getElementById('importConfirmModal').classList.add('hidden');
                    this.importedData = null;
                });

                document.getElementById('confirmClearData').addEventListener('click', () => {
                    this.clearAllData();
                });

                document.getElementById('cancelClearData').addEventListener('click', () => {
                    document.getElementById('clearDataConfirmModal').classList.add('hidden');
                });

                // 点击页面其他地方关闭下拉菜单
                document.addEventListener('click', (e) => {
                    if (!dataContainer.contains(e.target)) {
                        dataMenu.classList.add('hidden');
                    }
                });
            }

            // 增强版全屏星星爆炸特效
            createStarExplosion(x, y) {
                // 更多颜色选择
                const colors = [
                    '#FFD700', '#FFA500', '#FF6B6B', '#4ECDC4', '#45B7D1',
                    '#FF69B4', '#9B59B6', '#00FF7F', '#FF1493', '#FFDAB9',
                    '#E6E6FA', '#FFE4B5', '#DDA0DD', '#98FB98', '#87CEEB'
                ];

                // 创建背景闪光
                const flash = document.createElement('div');
                flash.className = 'screen-flash';
                document.body.appendChild(flash);
                setTimeout(() => flash.remove(), 1500);

                // 混合粒子类型
                const particleTypes = ['star', 'heart', 'diamond'];
                const particleCount = 64; // 更多粒子

                // 创建多层爆炸效果
                for (let layer = 0; layer < 3; layer++) {
                    const layerParticles = layer === 0 ? 24 : layer === 1 ? 24 : 16;

                    for (let i = 0; i < layerParticles; i++) {
                        const particle = document.createElement('div');
                        particle.className = 'star-particle';

                        // 随机选择粒子类型
                        const type = particleTypes[Math.floor(Math.random() * particleTypes.length)];
                        if (type !== 'star') {
                            particle.classList.add(type);
                        }

                        // 随机大小
                        const sizeClass = Math.random();
                        if (sizeClass < 0.3) {
                            particle.classList.add('large');
                        } else if (sizeClass > 0.7) {
                            particle.classList.add('small');
                        }

                        // 随机颜色
                        const color = colors[Math.floor(Math.random() * colors.length)];
                        particle.style.background = `linear-gradient(45deg, ${color}, ${this.adjustBrightness(color, -20)})`;
                        particle.style.color = color;

                        // 设置初始位置（屏幕中心）
                        const centerX = window.innerWidth / 2;
                        const centerY = window.innerHeight / 2;
                        particle.style.left = centerX + 'px';
                        particle.style.top = centerY + 'px';

                        // 计算爆炸方向和距离（分层）
                        const baseAngle = (Math.PI * 2 * i) / layerParticles;
                        const angleVariation = (Math.random() - 0.5) * 0.5;
                        const angle = baseAngle + angleVariation;

                        const baseDistance = 150 + layer * 100 + Math.random() * 100;
                        const velocity = baseDistance;
                        const tx = Math.cos(angle) * velocity;
                        const ty = Math.sin(angle) * velocity;

                        // 设置CSS变量
                        particle.style.setProperty('--tx', tx + 'px');
                        particle.style.setProperty('--ty', ty + 'px');

                        // 设置动画延迟（分层爆炸）
                        const delay = layer * 100;
                        particle.style.animation = `starExplosion 2s ease-out ${delay}ms forwards`;

                        document.body.appendChild(particle);

                        // 动画结束后移除
                        setTimeout(() => {
                            if (particle.parentNode) {
                                particle.parentNode.removeChild(particle);
                            }
                        }, 2500);
                    }
                }
            }

            // 调整颜色亮度
            adjustBrightness(color, amount) {
                const usePound = color[0] === '#';
                const col = usePound ? color.slice(1) : color;
                const num = parseInt(col, 16);
                let r = (num >> 16) + amount;
                let g = (num >> 8 & 0x00FF) + amount;
                let b = (num & 0x0000FF) + amount;
                r = r > 255 ? 255 : r < 0 ? 0 : r;
                g = g > 255 ? 255 : g < 0 ? 0 : g;
                b = b > 255 ? 255 : b < 0 ? 0 : b;
                return (usePound ? '#' : '') + (r << 16 | g << 8 | b).toString(16).padStart(6, '0');
            }

            // 播放mp3/success.wav音频文件
            playExplosionSound() {
                // 创建音频对象
                const audio = new Audio('mp3/success.wav');

                // 设置音量
                audio.volume = 0.6;

                // 播放音频
                audio.play().catch(error => {
                    console.log('音频播放失败:', error);
                    // 如果音频播放失败，回退到合成音效
                    this.playFallbackSound();
                });
            }

            // 回退音效（当音频文件无法播放时）
            playFallbackSound() {
                if (!this.audioContext) {
                    this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
                }

                const now = this.audioContext.currentTime;

                // 简单的成功音效
                const oscillator = this.audioContext.createOscillator();
                const gainNode = this.audioContext.createGain();

                oscillator.connect(gainNode);
                gainNode.connect(this.audioContext.destination);

                oscillator.frequency.setValueAtTime(523.25, now);
                oscillator.frequency.setValueAtTime(659.25, now + 0.1);
                oscillator.frequency.setValueAtTime(783.99, now + 0.2);

                gainNode.gain.setValueAtTime(0.3, now);
                gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.3);

                oscillator.start(now);
                oscillator.stop(now + 0.3);
            }

            // 增强版成功特效
            showSuccessEffect(element) {
                if (!element) return;

                // 播放爆炸音效
                this.playExplosionSound();

                // 添加成功发光效果
                element.classList.add('success-glow');
                setTimeout(() => {
                    element.classList.remove('success-glow');
                }, 1200);

                // 创建全屏爆炸效果
                setTimeout(() => {
                    this.createStarExplosion();
                }, 50);
            }

            // 初始化字母索引
            initAlphabetIndex() {
                const alphabetBtns = document.querySelectorAll('.alphabet-btn');
                const clearBtn = document.querySelector('.alphabet-clear');

                alphabetBtns.forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const letter = e.target.dataset.letter;
                        this.filterByLetter(letter);

                        // 更新选中状态
                        alphabetBtns.forEach(b => b.classList.remove('active'));
                        e.target.classList.add('active');
                    });
                });

                clearBtn.addEventListener('click', () => {
                    this.clearLetterFilter();
                    alphabetBtns.forEach(b => b.classList.remove('active'));
                });
            }

            // 按字母筛选学生
            filterByLetter(letter) {
                document.getElementById('searchInput').value = letter;
                this.renderStudentList();

                // 显示筛选提示
                this.showNotification(`已筛选字母 ${letter} 开头的学生`);
            }

            // 清除字母筛选
            clearLetterFilter() {
                document.getElementById('searchInput').value = null;
                this.renderStudentList();
                this.showNotification('已清除字母筛选');
            }


        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            const app = new StudentManager();
            app.initResponsiveLayout();
        });

        // 添加到StudentManager类中
        StudentManager.prototype.initResponsiveLayout = function () {
            // 初始调整
            this.adjustLayoutForScreenSize();

            // 监听窗口大小变化
            window.addEventListener('resize', () => {
                this.adjustLayoutForScreenSize();
            });
        };

        StudentManager.prototype.adjustLayoutForScreenSize = function () {
            const windowWidth = window.innerWidth;
            const mainContent = document.querySelector('main');
            const alphabetSidebar = document.querySelector('.alphabet-sidebar');

            // 调整主内容区域边距
            if (alphabetSidebar && !alphabetSidebar.classList.contains('hidden')) {
                if (windowWidth <= 768) {
                    mainContent.style.marginLeft = '0';
                } else if (windowWidth <= 1024) {
                    mainContent.style.marginLeft = '60px';
                } else if (windowWidth <= 1280) {
                    mainContent.style.marginLeft = '70px';
                } else {
                    mainContent.style.marginLeft = '80px';
                }
            } else {
                mainContent.style.marginLeft = '0';
            }

            // 确保响应式网格布局正确渲染
            this.renderStudentList();
        };
    </script>
</body>

</html>